import React,{Fragment, useEffect, useState} from 'react';
import { connect } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import * as actionCreators from './store/actionCreators';


import TxtHeader from '../../components/Header/TxtHeader';
import { dealRes, isMobile } from '../../utils/CommonUtils';
import { funcSliderRefresh, funcSliderValid } from '../../../api';

import { NoticeBar } from 'antd-mobile';
import { Account } from '../../../common/js/Options';


/**
 * 忘记密码 找回
 * @param {*} props 
 * @returns 
 */
const FindPwdTone = (props) => {

    const navigate = useNavigate();

    const { loginData, setData } = props;
    const [ curStep, setCurStep ] =  useState(1);
    const [ username, setUsername ] =  useState('');
    // 登录按钮禁用状态
    const [ disableBtn, setDisableBtn ] = useState(true);
    const noticeTitle = '仅限手机号已验证或者手机号注册用户找回密码';
    const [ dragTab, setDragTab ] = useState(false);
    const [ loadTab, setLoadTab ] = useState(false);
    // 滑块模块展示控制
    const [ sliderTab, setSliderTab ] = useState(false);
    // 滑块验证码 token
    const [ ticket, setTicket ] = useState('');
    const [ slBackIMG, setSlBackIMG ] = useState('');
    const [ sliderIMG, setSliderIMG ] = useState('');
    const [ small2Top, setSmall2Top ] = useState(0);
    const [ startPage, setStarPage ] = useState({ 'x' : 0 });    
    const [ offsetPage, setOffsetPage ] = useState({ 'x' : 0 }); 

    useEffect(() => {
        console.log( loginData );
        let loginName = '';
        if(loginData && isMobile(loginName = loginData.loginName)) {
            setUsername(loginName);
        }
    }, [ loginData ]);

    useEffect(()=> {}, [ username ]);
    useEffect(()=> {}, [ dragTab, startPage, offsetPage ]);
    useEffect(()=> {
        if(sliderTab) {
            refreshFunc();
        }
    }, [ disableBtn, sliderTab ]);

    // eslint-disable-next-line
    const toBack = () => navigate(-1);

    const handleInt = (e, name) => {
        const value = e.target.value;
        if ('username' === name) { setUsername(value); }
        if (value && value.length > 0) {
            setDisableBtn(false);
        } else {
            setDisableBtn(true);
        }
    }

    const doClear = (name) => {
        if ('username' === name) { setUsername(''); setDisableBtn(true);}
    }

    const doNext = () => {
        setSliderTab(true);
        setDisableBtn(true);
        // 设置传递参数
        setData(username);
    }

    const handleDown  = (e) => {
        setDragTab(true);
        setStarPage({ x: e.changedTouches[0].pageX });
    }

    const handleMove = (e) => {
        let lenx = e.changedTouches[0].pageX - startPage.x;
        setOffsetPage({ x : lenx})
    }

    /** ===================== 数据操作 ====================== */
    const handleUp = async (e) => {
        setDragTab(false);
        console.log('滑块移动的位置(x, y)->', '(' + offsetPage.x + ',' + small2Top + ')');
        const params = {};
        params.remark = ticket;
        params.remark1 = parseInt(offsetPage.x);
        const result = dealRes(await funcSliderValid(params));
        console.log('滑块移动-result->', result);
        if (result) {
            if(curStep === 1) {
                setSliderTab(false);
                setCurStep(curStep + 1);
                // 跳转到 身份验证页
                navigate('/authen');
            }
        } else {
            // 验证失败 加载中
            setLoadTab(true);
        }
        setOffsetPage({ x: 0 });
    }

    const refreshFunc = async () => {
        const params = {};
        const hua = (document.querySelector('.w-vli-body'));

        params.w = hua.clientWidth;
        params.h = parseInt(hua.clientWidth / 2.06);
        const result = dealRes(await funcSliderRefresh(params));
        if (result) {
            const { ticket, sliderY, slBackIMG, sliderIMG } = result;
            setTicket(ticket);
            setSmall2Top(sliderY);
            setSlBackIMG(slBackIMG);
            setSliderIMG(sliderIMG);
        }
    }
    /** ===================== 数据操作 ====================== */

    return (
        <Fragment>
            <div className='w-lay'>
                <TxtHeader desc='忘记密码' toBack={()=> toBack()}/>
                {/* 通知 */}
                <NoticeBar content={noticeTitle} color='alert' closeable/>
                <div className='w-find w-find-code'>
                    {/* 1. 账号 step = 1 */
                        curStep === 1 ? (
                            <div data-v2310001='' className='w-int-container'>
                                <label htmlFor={'username'} className='w-int-label' style={{ left: -10 }}><Account/></label>
                                <input 
                                    name='username' 
                                    value={username}
                                    data-v2310001=''
                                    autoComplete='off'
                                    placeholder='请输入账号名/邮箱/手机号'
                                    onChange={(e)=> handleInt(e, 'username')}
                                    className='w-int w-username'
                                />
                                <i data-v2310001='' className='w-int-icon w-int-clear' onClick={()=> doClear('username')}/>
                            </div>
                        ) : null
                    }

                    <div className='w-login-btn w-center'>
                        <button className={`w-btn w-mk-btn w-wd_10 w-ris-dot2${disableBtn ? ' w-disable' : ''}`}
                            onClick={()=> doNext(curStep)}>下一步</button>
                    </div>
                </div>
            </div>
            {
                sliderTab ? (
                    <div className='w-validate'>
                        <div className='w-vli-box'>
                            <div className='w-vli-modal w-mobile'>
                                <div>
                                    <div className='w-vli-head'>
                                        安全验证
                                        <img className='w-vli-refresh' 
                                            onClick={()=> refreshFunc()} src={require('../../../common/images/refresh.png')} alt=''/>
                                    </div>
                                    <div className='w-vli-body'>
                                        <div className='w-vli-load' style={{ display: loadTab ?'':'none', paddingTop: '20%' }}><p>加载中</p></div>
                                        {/* <img className='w-vli-img' src={require('../../../common/images/hua01.png')} alt=''/> */}
                                        <img className='w-vli-img' src={slBackIMG} alt=''/>
                                        <img className='w-vli-hua' src={sliderIMG} style={{left: offsetPage.x, height: 'auto', top: small2Top }} alt=''/>
                                        {/* <img className='w-vli-hua' style={{left: offsetPage.x}} src={require('../../../common/images/hua02.png')} alt=''/> */}
                                    </div>

                                    <div className='w-vli-foot'>
                                        <div data-v2310001='' className='w-vli-desc'>
                                            <span>推动滑块至正确区域</span>
                                            <div data-v2310001='' className='w-vli-hua-icon' />
                                            <img style={{ left: offsetPage.x }}
                                                onTouchEnd={e => handleUp(e)}
                                                onTouchStart={e => handleDown(e)} 
                                                onTouchMove={e => handleMove(e)} 
                                                src={require('../../../common/images/hua03.png')} alt=''/>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                ) : null
            }
            
        </Fragment>
    )
}

const stateToProps = (state) => {
    return {
        homeData: state.getIn(['home', 'homeData']),
        loginData: state.getIn(['login', 'loginData']),
    }
}

const state2Dispatch = (dispatch) => ({
    setData(data) {
        dispatch(actionCreators.setData(data))
    }
})

// const CustInput = (properties) => {
//     const { id, label, name, placeholder, className, type='text', value } = properties;
//     return (
//         <div data-v2310001='' className='w-int-container'>
//             <label htmlFor={name} className='w-int-label'>{label}</label>
//             <input 
//                 id={id} 
//                 name={name} 
//                 type={type}
//                 value={value}
//                 data-v2310001=''
//                 autoComplete='off'
//                 placeholder={placeholder}
//                 onChange={(e)=> handleInt(e, name)}
//                 className={`w-int ${className? className : ''}`}
//             />
//             <i data-v2310001='' className='w-int-icon w-int-clear' onClick={()=> doClear(name)}/>
//         </div>
//     )
// }

export default connect(stateToProps, state2Dispatch)(FindPwdTone);